//
//  ACAlarmListContoller.m
//  AlarmClock
//
//  Created by kai ren on 23/10/2011.
//  Copyright 2011 none. All rights reserved.
//

#import "ACAlarmListContoller.h"
#import <QuartzCore/QuartzCore.h>
#import "ACAlarmEditController.h"

@implementation ACAlarmListContoller

@synthesize alarms;

- (void)reloadView{
	UIBezierPath *path = [UIBezierPath bezierPath];	
	
	CGPoint topLeft		 = CGPointMake(0, -3);
	CGPoint bottomLeft	 = CGPointMake(-5, 100 * [alarms count] + 8);
	CGPoint bottomRight	 = CGPointMake(320, 100 * [alarms count] + 8);
	CGPoint topRight	 = CGPointMake(320, -3);
	
	[path moveToPoint:topLeft];
	[path addLineToPoint:bottomLeft];
	[path addLineToPoint:bottomRight];
	[path addLineToPoint:topRight];
	[path addLineToPoint:topLeft];
	
	[path closePath];
	
	self.tableView.layer.shadowPath = path.CGPath;	
}
- (void)getAlarms{
	NSString *docPath = getDocumentPath();
	NSArray *Contents = getContentsOfDocument();
	
	[alarms removeAllObjects];
	
	for (NSString *alarmName in Contents) {
		if (![alarmName hasSuffix:@".alarm"]) {
			continue;
		}
		
		ACAlarm *alarm = [[ACAlarm alloc] initWithPath:[NSString stringWithFormat:@"%@/%@", docPath, alarmName]];
		
		if (0 == [alarms count]) {
			[alarms addObject:alarm];
			continue;
		}
		
		for (int i = 0; i < [alarms count]; i++) {
			if (alarm.index < ((ACAlarm *)[alarms objectAtIndex:i]).index) {
				[alarms insertObject:alarm atIndex:i];
				break;
			} else if (i == [alarms count] - 1) {
				[alarms addObject:alarm];
				break;
			}
		}
		
		[alarm release];
	}
}

#pragma mark -
#pragma mark Button Event

- (void)add{
	ACAlarmEditController *editCtrl = [[ACAlarmEditController alloc] init];
	UINavigationController *ctrl = [[UINavigationController alloc] initWithRootViewController:editCtrl];
	
	[self presentModalViewController:ctrl animated:YES];
	[editCtrl release];
	
	[self setEditing:NO animated:YES];
}

- (void)viewDidLoad{
	[super viewDidLoad];
	
	//init data
	alarms = [[NSMutableArray alloc] initWithCapacity:0];
	
	//title
	self.title = NSLocalizedString(@"Shouting Alarm", nil);
	
	UIBarButtonItem *btnAdd = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
																			target:self 
																			action:@selector(add)];
	
	self.navigationItem.rightBarButtonItem = btnAdd;
	self.navigationItem.leftBarButtonItem = [self editButtonItem];
	
	[btnAdd release];
	
	//table
	self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	self.tableView.layer.shadowOffset = CGSizeMake(0, 0);
	self.tableView.layer.shadowRadius = 3;
	self.tableView.layer.shadowOpacity = 0.4;
	self.tableView.layer.shadowColor = [UIColor blackColor].CGColor;
	self.tableView.allowsSelectionDuringEditing = YES;
	self.view.backgroundColor = [UIColor clearColor];
	
	self.navigationController.view.backgroundColor = Background;
	}

- (void) viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];
	[self getAlarms];
	[self.tableView reloadData];
	[self reloadView];
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return [self.alarms count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d", indexPath.section, indexPath.row];
	
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	UILabel *lblTime;
	UILabel *lblRepeat;
	UILabel *lblTitle;
	UISwitch *alarmSwitch;
	UIView *bgView;
	ACAlarm *alarm = [alarms objectAtIndex:indexPath.row];
	
	if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
		
		lblTime = [[[UILabel alloc] initWithFrame:CGRectMake(10, 15, 100, 30)] autorelease];
		lblTime.font = [UIFont boldSystemFontOfSize:22];
		lblTime.textAlignment = UITextAlignmentLeft;
		lblTime.backgroundColor = [UIColor clearColor];
		lblTime.shadowColor = [UIColor colorWithWhite:0.8 alpha:0.8];
		lblTime.shadowOffset = CGSizeMake(0, -0.7);
		lblTime.tag = 2;
		[cell.contentView addSubview:lblTime];
		
		lblRepeat = [[[UILabel alloc] initWithFrame:CGRectMake(11, 45, 100, 20)] autorelease];
		lblRepeat.font = [UIFont boldSystemFontOfSize:14];
		lblRepeat.textAlignment = UITextAlignmentLeft;
		lblRepeat.backgroundColor = [UIColor clearColor];
		lblRepeat.shadowColor = [UIColor colorWithWhite:0.5 alpha:0.8];
		lblRepeat.shadowOffset = CGSizeMake(0, -0.7);
		lblRepeat.tag = 3;
		[cell.contentView addSubview:lblRepeat];
		
		lblTitle = [[[UILabel alloc] initWithFrame:CGRectMake(11, 65, 100, 20)] autorelease];
		lblTitle.font = [UIFont systemFontOfSize:14];
		lblTitle.textAlignment = UITextAlignmentLeft;
		lblTitle.backgroundColor = [UIColor clearColor];
		lblTitle.tag = 4;
		[cell.contentView addSubview:lblTitle];
		
		alarmSwitch = [[UISwitch alloc] init];
		alarmSwitch.center = CGPointMake(320 - alarmSwitch.frame.size.width/2 - 8, 50);
		alarmSwitch.tag = 5;
		[cell.contentView addSubview:alarmSwitch];
		
		bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
		bgView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tableBackground.png"]];
		[cell insertSubview:bgView atIndex:0];
    } else {
		lblTime = (UILabel *)[cell.contentView viewWithTag:2];
		lblRepeat = (UILabel *)[cell.contentView viewWithTag:3];
		lblTitle = (UILabel *)[cell.contentView viewWithTag:4];
		alarmSwitch = (UISwitch *)[cell.contentView viewWithTag:5];
		[alarmSwitch removeTarget:nil action:NULL forControlEvents:UIControlEventValueChanged];
	}
	
	NSMutableString *strTime = [NSMutableString stringWithFormat:@"%d",alarm.index];
	
	while ([strTime length] < 3) {
		[strTime insertString:@"0" atIndex:0];
	}

	[strTime insertString:@":" atIndex:[strTime length] - 2];
	
	lblTime.text = strTime;
	lblRepeat.text = stringOfRepeat(alarm);
	lblTitle.text = alarm.title;
	alarmSwitch.on = alarm.isActive;
	[alarmSwitch addTarget:alarm action:@selector(switchAlarm:) forControlEvents:UIControlEventValueChanged];
	
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return 100;
}

- (void) tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
 forRowAtIndexPath:(NSIndexPath *)indexPath
{	
	[(ACAlarm *)[alarms objectAtIndex:indexPath.row] deleteAlarm];
	[alarms removeObjectAtIndex:indexPath.row];
	[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
	[self reloadView];
}

- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	UISwitch *alarmSwitch = (UISwitch *)[cell.contentView viewWithTag:5];
	if (alarmSwitch.hidden && !tableView.editing) {
		alarmSwitch.hidden = NO;
	} else {
		alarmSwitch.hidden = YES;
	}
		
	return YES;
}

#pragma mark -
#pragma mark UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	if (tableView.editing) {
		ACAlarmEditController *editCtrl = [[ACAlarmEditController alloc] initWithAlarm:[alarms objectAtIndex:indexPath.row]];
		UINavigationController *ctrl = [[UINavigationController alloc] initWithRootViewController:editCtrl];
		
		[self presentModalViewController:ctrl animated:YES];
		[editCtrl release];
	
		[self setEditing:NO animated:YES];
	}
}

@end
